#include "MainDialog.h"
#include "ui_MainDialog.h"
#include <iostream>
#include "NotreDameLoader.h"

using namespace std;

MainDialog::MainDialog(QWidget *parent) : QDialog(parent), ui(new Ui::MainDialog)
{
    ui->setupUi(this);

    connect(ui->loadingImageButton, SIGNAL(clicked()), this, SLOT(clickedImageLoadButton()));
    connect(ui->loadingPreprocessedButton, SIGNAL(clicked()), this, SLOT(clickedPreprocessedDataButton()));

    // Unit Testing
    //unitTest();
}

MainDialog::~MainDialog()
{
    delete ui;
}

void MainDialog::clickedImageLoadButton()
{
    ImageLoader loader;
    loader.load(); // all the images into Mat images

    if ( loader.getFiles().size() < 2 || loader.getInitialIndex().size() < 2)
    {
        cout << " Not enough images selected! " << endl;
        return;
    }

    Analyser analyser(loader.getFiles(), loader.getInitialIndex());
    //analyser.testNotreDame();
    analyser.analyse();

    cout << "!!! DONE !!!" << endl;

    VisualiserDialog * pDialog = new VisualiserDialog(this, NULL, &analyser);

    pDialog->setVisible(true);
}

void MainDialog::clickedPreprocessedDataButton()
{
    //NotreDameLoader loader;
    //loader.load();

    PreprocessedDataLoader loader;
    loader.load();

    QList<Camera> cameras = loader.getCameras();

    for(int i=0; i < cameras.size(); i++)
    {
        Camera c = cameras[i];

        cout << "Camera [" << i << "] "
             << c.getCameraPosition().getX() << ","
             << c.getCameraPosition().getY() << ","
             << c.getCameraPosition().getZ() << endl;
    }

    VisualiserDialog * pDialog = new VisualiserDialog(this, &loader, NULL);
    pDialog->setVisible(true);
}

void MainDialog::unitTest()
{
    // Testing PreprocessedFile

    // Test 1. writing test

    PreprocessedFile file;

    QList<Camera> cameras;
    PointCloud pointCloud;
    QList<Point3D> points;

    Camera camera;
    QString str;
    QString prefix = "Test_";

    /*
    for(int i=0; i < 1000; i++)
    {
        camera.setFilename(prefix + str.setNum(i));
        camera.setPespective(Point3D(i, i, i),
                             Point3D(i, i, i),
                             Point3D(i, i, i),
                             Point3D(i, i, i),
                             i);

        cameras.append(camera);

        points.append(Point3D(i, i, i));
    }
    */

    pointCloud.setPoints(points);

    file.setCameras(cameras);
    file.setPointCloud(pointCloud);

    file.save("test.pcd");

    // Test 2. reading test result

    PreprocessedFile file2;

    file2.load("test.pcd");

    if ( file.getPointCloud().getPointCount() == file2.getPointCloud().getPointCount())
    {
        int i = 0;
        i ++;
    }
}
